Thumb

How to pass ViewBag from controller to view using Asp.Net MVC4


7/1/2016 12:00:00 AM

Download Project

Step-1:

  • Open Visual studio
  • Click on “File”>New>Project>Visual c#>Web> then provide your project name> then select “ok”> then click “MVC”>ok.
  • Go to “HomeController”  and delete the default “ActionMethod” as like video.
  • Go to “Views”>”Home” folder and delete default views.
  • Create an Action method name “Index” into “HomeController”.
        public ActionResult Index()
        {
            ContactDBEntities db = new ContactDBEntities();
            ViewBag.ItemData = db.tblAddresses.ToList();
            return View();
        }

Step-2:

  • We have already created Database(We were provide you this Database with project, the folder name “DataBase” into project.click to download the full project
  • Now we will include the created database to ADO.NET Entity Framework.(It’s very easy way to use).
  • Right click on folder named “Model”>Add>New Item>ADO.NET Entity DataModel>ok>Generate from database>next>New connection>Provide your SQL Server name to “Server name” textfield>Select database from “database name”>ok>next
  • Expand “table”>expand “dbo”>select your created table>“finish

Step-3:

Index.cshtml

<div class="container">
    <h2>Basic Table</h2>
    <table class="table">
        <thead>
            <tr>
                <th>Id</th>
                <th>Name</th>
                <th>City</th>
            </tr>
        </thead>
        <tbody>
            @foreach (var data in ViewBag.ItemData)
            {
                <tr>
                    <td>@data.Id</td>
                    <td>@data.Name</td>
                    <td>@data.City</td>
                </tr>
            }
        </tbody>
    </table>
</div>

Now run the project and you will only be able to see the list of data from database.

About Teacher

Reza Karim

Software Engineer

More about him